﻿#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 ZHENG Zhong <http://www.zhengzhong.net/>
#
# Created on 2008-04-28.
# $Id$
#

"""Bootstrap for running a Django application on Google App Engine.
"""

import logging
import os
import sys

import google.appengine.ext.webapp.util

#---------------------------------------------------------------------------------------------------
# Adapting Django 1.0 (django_1_0_2.zip) to Google App Engine
#---------------------------------------------------------------------------------------------------

#
# Replace Google App Engine's Django.
#

_DJANGO_ZIP_FILE = 'django_1_0_2.zip'
_WEBAPP_ROOT_DIR = os.path.abspath(os.path.dirname(__file__))

django_zip_path = os.path.join(_WEBAPP_ROOT_DIR, _DJANGO_ZIP_FILE)
if os.path.isfile(django_zip_path):
    # Remove the standard version of Django.
    for m in [m for m in sys.modules if m.startswith('django')]:
        del sys.modules[m]
    # Force sys.path to have our own Django (zip file) first.
    sys.path.insert(0, django_zip_path)
    logging.info('Loading Django (zip file) from: %s' % django_zip_path)
else:
    logging.error('Failed to find Django zip file at %s' % django_zip_path)

# We must set this environment variable BEFORE importing any part of Django.
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

# Django 1.0 imports.
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher

# Set the logging level on the root logger.
if os.environ.get('SERVER_NAME') == 'localhost':
    logging.getLogger().setLevel(logging.DEBUG)
else:
    logging.getLogger().setLevel(logging.INFO)


def log_exception(sender, **kwds):
    logging.exception('Error occurred in request:')

# Update Django signal listeners.
django.core.signals.got_request_exception.disconnect(django.db._rollback_on_exception)
django.core.signals.got_request_exception.connect(log_exception)


#---------------------------------------------------------------------------------------------------
# main entry point
#---------------------------------------------------------------------------------------------------

def main():
    # Create a Django application for WSGI.
    application = django.core.handlers.wsgi.WSGIHandler()
    # Run the WSGI CGI handler with that application.
    google.appengine.ext.webapp.util.run_wsgi_app(application)


if __name__ == '__main__':
    main()




